package com.ningxun.rms.web.controller.wechatdept;

import com.ningxun.rms.common.core.domain.entity.SysUser;
import com.ningxun.rms.system.service.ISysDeptService;
import com.ningxun.rms.common.core.domain.entity.SysDept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.HashMap;
import java.util.Map;
import com.ningxun.rms.common.utils.SecurityUtils;
import com.ningxun.rms.common.core.domain.model.LoginUser;

@RestController
@RequestMapping("/wechat/dept")
public class WechatDeptController {

    @Autowired
    private ISysDeptService deptService;

    /**
     * 用户端获取地市列表（只返回必要字段）
     */
    @GetMapping("/list")
    public Map<String, Object> getDeptList() {
        // 1. 查询所有 parentId = 100 的城市，只返回状态正常的
        SysDept deptQuery = new SysDept();
        deptQuery.setParentId(100L);
        deptQuery.setStatus("0"); // 只查正常
        List<SysDept> deptList = deptService.selectDeptList(deptQuery);
        List<DeptVO> voList = deptList.stream()
                .map(d -> new DeptVO(d.getDeptId(), d.getDeptName()))
                .collect(Collectors.toList());

        // 2. 单独获取 "全部地市" (dept_id = 100)，避免重复添加
        SysDept allDepts = deptService.selectDeptById(100L);
        boolean hasAllDepts = voList.stream().anyMatch(vo -> vo.getDeptId().equals(100L));
        if (allDepts != null && !hasAllDepts && "0".equals(allDepts.getStatus())) {
            voList.add(0, new DeptVO(allDepts.getDeptId(), allDepts.getDeptName()));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "操作成功");
        result.put("data", voList);
        return result;
    }

    /**
     * 根据部门ID获取单个地市信息（只返回必要字段）
     */
    @GetMapping("/list/{deptId}")
    public DeptVO getDeptById(@PathVariable("deptId") Long deptId) {
        SysDept dept = deptService.selectDeptById(deptId);
        if (dept == null) {
            return null;
        }

        return new DeptVO(dept.getDeptId(), dept.getDeptName());
    }

    // 简单VO对象，只返回需要的字段（字段名为 deptId、deptName）
    public static class DeptVO {
        private Long deptId;
        private String deptName;

        public DeptVO(Long deptId, String deptName) {
            this.deptId = deptId;
            this.deptName = deptName;
        }
        public Long getDeptId() { return deptId; }
        public String getDeptName() { return deptName; }
        public void setDeptId(Long deptId) { this.deptId = deptId; }
        public void setDeptName(String deptName) { this.deptName = deptName; }
    }
} 